
class ItemsController < ApplicationController
  # GET /items
  # GET /items.xml
  
  before_filter :checkPermission, :except=>[:index,:new,:copy]

  in_place_edit_for :owner, :titel

  def index

    @rolle = getRolle(params[:r])
    @items = @owner.items.find(:all, :order => "number ASC")
    
    #remove the marked to delete
    @items.each do |item|
      item.destroy if item.deleted?
    end
    @items = @owner.items.find(:all, :order => "number ASC")
   @owner.titel = "NoName" if  @owner.titel.nil? or @owner.titel==""
   @owner.save() if !@owner.new_record?
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @items }
    end
  end

  # GET /items/1
  # GET /items/1.xml
  def show
    @rolle = getRolle(params[:r])
    @item = @owner.items.find(params[:id]) if @rolle
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @item }
    end
  end
  def copy
    
    
    @rolle = getRolle(params[:r])
    conditions = ["activ = ?", true] if !(@rolle == 'checker' or  @rolle == 'owner')
    @items = @owner.items.find(:all, :order => "number ASC", :conditions => conditions)
    newOwner = Owner.new
    newOwner.titel =  "#{@owner.titel} copy"
    newOwner.inhaber="#{Time.now}$%&/(#{newOwner.titel}'+*._#{request.env["REMOTE_ADDR"]}"
    @items.each{|i|
      newOwner.items << Item.create(:check=>i.check,:description=>i.description,:activ=>i.activ,
                                    :number=>i.number,:shift=>i.shift,:deleted=>i.deleted)
    }
    if newOwner.save
      flash[:notice] = 'Items wurden kopiert.<br/>'
      redirect_to("/items/?r=#{newOwner.inhaber}")
    else
      flash[:notice] = 'Items wurden nicht kopiert.<br/>'
      redirect_to("/items/?r=#{params[:r]}")
    end
  end
  # GET /items/new
  # GET /items/new.xml
  def new
    
    newOwner = Owner.create(:titel=>"New Checklist", :inhaber=>"#{Time.now}$%&/(dfghwertdfhdgstere'+*._#{request.env["REMOTE_ADDR"]}")
    newOwner.items << Item.create(:check=>false,:description=>'Double-Click me!',:activ=>true,
                                    :number=>0,:shift=>0,:deleted=>false)

    newOwner.save
    redirect_to("/items/?r=#{newOwner.inhaber}") 
  end

  # GET /items/1/edit
  def edit
    @rolle = getRolle(params[:r])
    @item = @owner.items.find(params[:id]) if !@owner.new_record? and @rolle != "gast"

  end

  # POST /items
  # POST /items.xml
  def create
   @item = Item.new(params[:item])
   @rolle = getRolle(params[:r])
   last = @owner.items.find(:last)
   @item.number = last.id if last
   @item.activ = true
   @owner.titel = "New Checklist" if @owner.titel.nil?
  
    @owner.inhaber="#{Time.now}$%&/(#{@item.description}'+*._#{request.env["REMOTE_ADDR"]}" if( @rolle != "owner")
    @owner.items << @item
    respond_to do |format|
      if @owner.save
        flash[:notice] = 'Item was successfully created.<br/>'
      
        format.html { redirect_to("/items/?r=#{@owner.inhaber}") }
        format.xml  { render :xml => @item, :status => :created, :location => @item }
        format.js
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @item.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  def add_item
    @item = Item.new
    @rolle = getRolle(params[:r])
    last = @owner.items.find(:last)
    @item.number = last.id if last
    @item.description = params[:value] 
    @owner.items << @item
    @owner.save!
    respond_to do |format|
      format.js{ render :partial => @item}
    end
   
  end
 
  # PUT /items/1
  # PUT /items/1.xml
  def update
  #  render :layout => false if request.xhr?
    @rolle = getRolle(params[:r])
    @item = @owner.items.find(params[:id]) if @rolle and @rolle != "gast"
    if @item
    respond_to do |format|
      if request.xhr?
        @item.update_attributes(:check=>params[:value_check])
        @item.update_attributes(:activ=>params[:value_activ])
       
        format.js{ render :partial => "item"}
      else
          if @item.update_attributes(params[:item])
        flash[:notice] = 'Item was successfully updated.'
        format.html {redirect_to("/items/?r=#{params[:r]}") }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @item.errors, :status => :unprocessable_entity }
      end
      redirect_to("/items")
      end
    
    end
  else
     flash[:notice] = 'Item wurde nicht gefunden.'
  end
   
 end
 
 
 def left 
    @rolle = getRolle(params[:r])
    @item = @owner.items.find(params[:id]) if @rolle and @rolle == "owner"
    if @item
      @item.update_attributes(:shift=>(@item.shift - 20))
      respond_to do |format|
        if request.xhr?
          format.js{ render :partial => "item"}
        end
      end
    else
      redirect_to("/items")
    end
  end
  
  def right 
    @rolle = getRolle(params[:r])
    @item = @owner.items.find(params[:id]) if @rolle and @rolle == "owner"
    if (@item && (!@item.shift || @item.shift < 40))
      if(!@item.shift)
        @item.update_attributes(:shift=>20)
      else
        @item.update_attributes(:shift=>(@item.shift + 20))
      end
      respond_to do |format|
        if request.xhr?
          format.js{ render :partial => "item"}
        end
      end
    else
      redirect_to("/items")
    end
  end

  def descriptoin_edit 
    @rolle = getRolle(params[:r])
    @item = @owner.items.find(params[:id]) if @rolle and @rolle != "gast"
    if @item
      respond_to do |format|
        if request.xhr?
          format.js{ render :partial => "description_edit"}
        end
      end
    else
      redirect_to("/items")
    end
  end
    def shiftItems
   #   print "#################### shift items  ################"
        if request.xhr?
          from = params[:from].to_i
          to = params[:to].to_i
           @rolle = getRolle(params[:r])
           if @rolle and @rolle != "gast"
              item_from = @owner.items.find(from)
              if to == 0
                item_to = @owner.items.find(:first, :order => "number ASC")
              else
                item_to = @owner.items.find(to) 
              end
              if item_from and item_to
                @items = @owner.items.find(:all, :order => "number ASC")
                if item_from.number <= item_to.number
                  items_to_shift = @items.select {|i| i.number >= item_from.number and i.number<=item_to.number}
                  right = false
                else
                  items_to_shift = @items.select {|i| i.number > item_to.number and i.number <= item_from.number}
                  right = true
                  items_to_shift.insert(0, @items[0]) if to == 0
                end
                order = items_to_shift.collect {|a| a.number } 
                items = right ? shiftRight(items_to_shift) : shiftLeft(items_to_shift)
                Item.transaction do
                (0 .. items.length-1).each{|i|
                 items[i].number = order[i]
                 items[i].save
                }
                end
                 js_items = (@owner.items.find(:all, :order => "number ASC")).collect {|i| i.id }
                  respond_to do |format|
                    format.js {render :json => js_items}
                    format.json {render :json => js_items}
                  end
        end
    end
  end
rescue
 @items = @owner.items.find(:all, :order => "number ASC")
 @error = "ERROR. Es ist ein Fehler aufgetaucht."
   respond_to do |format|
                    format.js {render :partial=>'list_item'}
                  end
  end
  def descriptoin_show
    @rolle = getRolle(params[:r])
    @item = @owner.items.find(params[:id]) if @rolle and @rolle != "gast"
    if @item
      @item.description = params[:value]
      print "-----------------------------------   #{params[:value].inspect}"
      @item.save
      respond_to do |format|
        if request.xhr?
          format.js{ render :partial => "description_show"}
        end
      end
    else
      redirect_to("/items")
    end
    end

# Titel in Place Editor
 def titel_edit 
    @rolle = getRolle(params[:r])
    if @owner
      respond_to do |format|
        if request.xhr?
          format.js{ render :partial => "titel_edit"}
        end
      end
    else
      redirect_to("/items")
    end
  end
  
  def titel_show
    @rolle = getRolle(params[:r])
    if @owner
      @owner.titel = params[:value]
      @owner.titel = "NoName" if  @owner.titel.nil? or @owner.titel==""
      @owner.save
      respond_to do |format|
        if request.xhr?
          format.js{ render :partial => "titel_show"}
        end
      end
    else
      redirect_to("/items")
    end
    end


  def check_all
    @rolle = getRolle(params[:r])
    @items = @owner.items.find(:all, :order => "number ASC")
    @items.each do |item|
     item.update_attributes(:check=>true)
   end
   
   flash[:notice] = 'All Checked.'
   
   respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @items }
    end   
  end

  # DELETE /items/1
  # DELETE /items/1.xml
  def destroy
    @owner = Owner.find_by_inhaber params[:r]
    @item = @owner.items.find(params[:id]) 
    #@item.destroy if @item
    if @item
      @item.deleted = true
      @item.save
    end

    respond_to do |format|
      if request.xhr?
        format.js{ render :partial => "delete"}
      else
        format.html { redirect_to("/items/?r=#{params[:r]}") }
        format.xml  { head :ok }
      end
    end
  end

  # UNDELETE /items/1.xml
  def undelete
    @owner = Owner.find_by_inhaber params[:r]
    @item = @owner.items.find(params[:id])
    @rolle = getRolle(params[:r])
    #@item.destroy if @item
    if @item
      @item.deleted = false
      @item.save
    end
    
    respond_to do |format|
      if request.xhr?
        format.js{ render :partial => "item"}
      else
        format.html { redirect_to("/items/?r=#{params[:r]}") }
        format.xml  { head :ok }
      end
    end
  end

  private 
  # [1,2,3,4,5,6] => [2,3,4,5,6,1]
  def shiftLeft array
    return array[1 .. -1] << array[0]
  end
  # [1,2,3,4,5,6] => [6,1,2,3,4,5]
  def shiftRight array
    return array[0 .. -2].insert(0, array[-1])
  end
  def getRolle param
    param =  "" if param.nil?
    if param.length==8
      @owner = Owner.find_by_gast param
      return "gast" if @owner 
    end
    if param.length==16
      @owner = Owner.find_by_checker param
       return "checker"  if @owner
    end
    if param.length==32
       @owner = Owner.find_by_inhaber param
       return "owner"  if @owner
   end
   @owner=Owner.new
   return ""
 end
 
 def checkPermission
  @rolle = getRolle(params[:r])
  if(!(@rolle == "checker" && params[:action] == "update") && @rolle != "owner")
    if request.xhr?
      render :template=> '/items/error',:layout=>false
    else
      render :template=> '/items/error'
    end
    
  end
 end


end


